<template>
  <textarea
    v-if="isEditing && type === 'textarea'"
    ref="input"
    class="cell-input"
    v-model="value"
    :placeholder="placeholder"
    :maxlength="maxlength"
    @keydown.tab.prevent="$emit('tab', $event)"
    @blur="onblur"
    @mousedown.stop
  />

  <input
    v-else-if="isEditing"
    ref="input"
    class="cell-input"
    v-model="value"
    :placeholder="placeholder"
    :maxlength="maxlength"
    @keydown.tab.prevent="$emit('tab', $event)"
    @blur="onblur"
    @mousedown.stop
  />

  <div v-else-if="value" class="cell-text" :style="{ maxHeight: `${height}px` }">{{ value }}</div>

  <div v-else-if="placeholder" class="cell-text cell-placeholder" :style="{ maxHeight: `${height}px` }">
    {{ placeholder }}
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref, watch } from 'vue'
import config from '@/config'
import { TableDefault } from '@/types'

export default defineComponent({
  name: 'CellEditor',

  model: {
    prop: 'val',
    event: 'input'
  },

  props: {
    /** 编辑框类型 */
    type: {
      type: String as PropType<'input' | 'textarea'>,
      default: 'textarea'
    },

    /** 编辑值 */
    val: {
      type: String,
      default: ''
    },

    /** 文本最大长度 */
    maxlength: {
      type: Number,
      default: config.tableOption.cellValueMaxLength
    },

    /** 占位文本 */
    placeholder: {
      type: String,
      default: ''
    },

    /** 编辑中 */
    editing: {
      type: Boolean,
      default: false
    },

    /** 高度 */
    height: {
      type: Number,
      default: TableDefault.rowHeight
    }
  },

  setup(props, { emit }) {
    /** 填写值 */
    const value = computed({
      get: () => props.val,
      set: val => emit('input', val)
    })

    /** 编辑中 */
    const isEditing = computed({
      get: () => props.editing,
      set: val => emit('update:editing', val)
    })

    /** 输入框 */
    const input = ref<null | HTMLTextAreaElement>(null)

    /** 开启编辑后自动聚焦 */
    watch(input, el => el?.focus())

    return {
      /** 填写值 */
      value,

      /** 编辑中 */
      isEditing,

      /** 输入框 */
      input,

      /** 失去焦点 */
      onblur() {
        isEditing.value = false
        value.value = value.value.trim()
      }
    }
  }
})
</script>

<style lang="scss">
.fa-widget-table-main {
  .cell-text {
    padding: 0 4px;
    // 默认隐藏滚动条，鼠标经过出现
    // 避免 Mac 下始终出现滚动条
    overflow-y: hidden;
    line-height: 1;
    transition: all ease-in-out 0.25s;

    &:hover {
      overflow-y: auto;
    }
  }

  .cell-input {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 0 0 0 4px;
    font-family: inherit;
    line-height: 1;
    border: none;
    outline: 2px solid #e9e9e9;
    resize: none;

    &::placeholder {
      color: $color-text-placeholder;
    }
  }

  .cell-placeholder {
    color: $color-text-placeholder;
  }
}
</style>
